// src/server.js

// ✅ 加载正确的 .env 文件（根据 NODE_ENV）
let envFile = '.env';
if (process.env.NODE_ENV === 'production') envFile = '.env.production';
else if (process.env.NODE_ENV === 'staging') envFile = '.env.staging';

require('dotenv').config({ path: envFile });
console.log(`🧪 使用环境配置文件: ${envFile}`);

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const mongoose = require('mongoose');
const portfinder = require('portfinder');
const config = require('./config');
const routes = require('./routes');
const { initSocket } = require('./services/socketService');
const { logger } = require('./utils/logger');
const errorHandler = require('./utils/errorHandler');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: { origin: config.corsOrigin, methods: ['GET', 'POST'] }
});

// 中间件
app.use(express.json());
app.use((req, res, next) => {
  logger.info(`${req.method} ${req.url}`);
  next();
});

// 路由
app.use('/api/v1', routes);

// 健康检查
app.get('/', (req, res) => {
  res.send('🚀 Maiya-IM 服务器运行正常！');
});
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'OK', uptime: process.uptime() });
});

// 错误处理
app.use(errorHandler);

// 数据库连接
mongoose
  .connect(config.mongodbUri)
  .then(() => logger.info('MongoDB connected'))
  .catch((err) => logger.error('MongoDB connection error:', err));

// Socket.IO 初始化
initSocket(io);

// 启动服务器
const PORT = process.env.PORT || 3000;

const startServer = async () => {
  try {
    server.listen(PORT, '0.0.0.0', () => {
      logger.info(`✅ Server running on http://0.0.0.0:${PORT}`);
    });
  } catch (err) {
    logger.error('Failed to start server:', err);
    process.exit(1);
  }
};

startServer();

// 捕获未处理的错误
process.on('uncaughtException', (err) => {
  logger.error('Uncaught Exception:', err);
  process.exit(1);
});

process.on('unhandledRejection', (err) => {
  logger.error('Unhandled Rejection:', err);
  process.exit(1);
});